package com.chen.web_chat.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chen.web_chat.entity.dto.LoginDto;
import com.chen.web_chat.entity.pojo.UserInfo;
import com.chen.web_chat.entity.enumerate.ResultCodeEnum;
import com.chen.web_chat.entity.vo.LoginVo;
import com.chen.web_chat.execption.MyException;
import com.chen.web_chat.mapper.UserInfoMapper;
import com.chen.web_chat.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    public LoginVo login(LoginDto loginDTO) {
        //获取输入验证码和存储得到redis的key名称
        String verificationCode = loginDTO.getVerificationCode();
        String verificationCodeKey = loginDTO.getVerificationCodeKey();
        String redisVerificationCode= redisTemplate.opsForValue().get("webChatUser:validate:" + verificationCodeKey);

        //根据获取的验证码和redis存储验证码是否一致
        if (StrUtil.isEmpty(redisVerificationCode) || !StrUtil.equalsIgnoreCase(redisVerificationCode, verificationCode)) {
            //如果不一致，提示用户验证码校验失败
           throw new MyException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //如果验证则删除redis里面的验证码
        redisTemplate.delete("webChatUser:validate:" + verificationCodeKey);

        //根据账号查询用户数据
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>()
                .eq("account",loginDTO.getAccount()));

        //如果用户名不存在直接返回报错
        if (userInfo == null) {
            throw new MyException(ResultCodeEnum.LOGIN_ERROR);
        }

        //如果存在，获取输入密码，比较输入密码和数据库密码是否一致
        //把输入密码加密，再比较数据库密码，md5
        String database_password = userInfo.getPassword();
        String input_password = loginDTO.getPassword();
        input_password = DigestUtils.md5DigestAsHex(input_password.getBytes());
        if (!input_password.equals(database_password)) {
            throw new MyException(ResultCodeEnum.LOGIN_ERROR);
        }

        //如果密码一致则登录成功，生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        //把登录成功用户信息放到redis里面
        redisTemplate.opsForValue().set("webChatUser:userInfo" + token,
                JSON.toJSONString(userInfo),
                60,
                TimeUnit.MINUTES
        );
        //返回loginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }
}
